package com.lz.sports.ui.config

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.lz.comm.BR
import com.lz.library.base.BaseActivity
import com.lz.library.extension.click
import com.lz.library.extension.resString
import com.lz.library.extension.showToast
import com.lz.library.extension.startActivity
import com.lz.sports.R
import com.lz.sports.bean.ParcelableString
import com.lz.sports.core.ProjectManager
import com.lz.sports.databinding.ActConfigBinding
import com.lz.sports.dialog.ParcelableSelectDialog
import com.lz.sports.vm.config.ConfigViewModel
import com.lz.ub.UBCManager
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

//项目配置
class ConfigActivity : BaseActivity<ConfigViewModel, ActConfigBinding>(), ParcelableSelectDialog.OnSelectedListener {

    override fun getLayoutRes(): Int = R.layout.act_config

    override fun getVMVariableId(): Int = BR.vm

    override fun initData(savedState: Bundle?) {
        lifecycleScope.launch {
            arrayOf(binding.tvSwitch, binding.flDevice, binding.flManager, binding.flScore, binding.flExam)
                .click().collect { onClick(it) }
        }
    }

    private fun onClick(v: View) {
        when (v.id) {
            R.id.tv_switch -> {
                val areaList = ProjectManager.examPlan?.examProjectList
                if (areaList != null && areaList.isNotEmpty()) {
                    ParcelableSelectDialog.show(this@ConfigActivity, R.string.select.resString(),
                        ProjectManager.currentExamProject, areaList as ArrayList<out ParcelableString>
                    )
                }
            }
            R.id.fl_device -> {
                if (ProjectManager.hasProjectInit()) {
                    if (UBCManager.get().isOpened()) {
                        startActivity(DeviceEnterActivity::class.java)
                    } else {
                        R.string.usbUnEnabled.showToast()
                    }
                }
            }
            R.id.fl_manager -> {
                if (ProjectManager.hasProjectInit()) {
                    startActivity(DeviceManagerActivity::class.java)
                }
            }
            R.id.fl_score -> {
                if (ProjectManager.hasProjectInit()) {
                    startActivity(ScoreRuleActivity::class.java)
                }
            }
            R.id.fl_exam -> {
                if (ProjectManager.hasProjectInit()) {
                    startActivity(ExamRuleActivity::class.java)
                }
            }
        }
    }

    override fun onSelected(dialog: ParcelableSelectDialog, position: Int, requestCode: Int) {
        dialog.dismiss()
        viewModel.selectProject(position)
    }
}